package com.hzy.utils;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.hzy.constant.ConfigConstants;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpStatus;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.SecureRandom;

@SuppressWarnings("AliDeprecation")
public class HttpUtils {

    public static SendSmsResponse login(String phone, String sms) throws ClientException {
        return sendSMS(phone, sms, ConfigConstants.sms_template_code_login);
    }

    public static boolean register(String phone, String sms) {
        try {
            SendSmsResponse response = sendSMS(phone, sms, ConfigConstants.sms_template_code_login);
            if ("OK".equals(response.getCode())) {
                return true;
            }
            return false;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }

//    public static SendSmsResponse finpwd(String phone, String sms) throws ClientException {
//        return sendSMS(phone, sms, ConfigConstants.sms_template_code_findpwd);
//    }

    public static SendSmsResponse bandPhone(String phone, String sms) throws ClientException {
        return sendSMS(phone, sms, ConfigConstants.sms_template_code_bandPhone);
    }

    /**
     * 功能描述: 根据手机号和action发送验证码。action：0注册 1绑定 2忘记密码 3登录
     *
     * @Param: [phone, sms, action] [手机号，短信内容，功能]
     * @Return: com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse
     * @Author: yy
     * @Date: 2018/11/16 15:33
     */
    @SuppressWarnings("Duplicates")
    public static boolean sendSmsResponse(String phone, String sms, int action) {
        switch (action) {
            case 0:
                try {
                    SendSmsResponse response = sendSMS(phone, sms, ConfigConstants.sms_template_code_register);
                    return "OK".equals(response.getCode());
                } catch (ClientException e) {
                    e.printStackTrace();
                    return false;
                }
            case 1:
                try {
                    SendSmsResponse response = sendSMS(phone, sms, ConfigConstants.sms_template_code_bandPhone);
                    return "OK".equals(response.getCode());
                } catch (ClientException e) {
                    e.printStackTrace();
                    return false;
                }
            case 2:
                try {
                    SendSmsResponse response = sendSMS(phone, sms, ConfigConstants.sms_template_code_findpwd);
                    return "OK".equals(response.getCode());
                } catch (ClientException e) {
                    e.printStackTrace();
                    return false;
                }
            case 3:
                try {
                    SendSmsResponse response = sendSMS(phone, sms, ConfigConstants.sms_template_code_login);
                    return "OK".equals(response.getCode());
                } catch (ClientException e) {
                    e.printStackTrace();
                    return false;
                }
//            case 4:
//                try {
//                    SendSmsResponse response = sendSMS(phone, sms, ConfigConstants.sms_template_code_register);
//                    return "OK".equals(response.getCode());
//                } catch (ClientException e) {
//                    e.printStackTrace();
//                    return false;
//                }
            default: break;
        }
        return false;
    }

    public static boolean registerDissHao(String phone, String sms) {
        try {
            SendSmsResponse response = sendSMS(phone, sms, ConfigConstants.sms_template_code_login);
            if ("OK".equals(response.getCode())) {
                return true;
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static SendSmsResponse sendSMS(String phone, String sms, String template) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ConfigConstants.accessKeyId, ConfigConstants.accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", ConfigConstants.sms_product, ConfigConstants.sms_domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(ConfigConstants.sms_end);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(template);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\"" + sms + "\"}");
        return acsClient.getAcsResponse(request);

    }

    private static final String BANK_STRING = "{\"CDB\":\"国家开发银行\",\"KLB\":\"昆仑银行\",\"BOYK\":\"营口银行\",\"JJBANK\":\"九江银行\",\"GDB\":\"广东发展银行\",\"CGNB\":\"南充市商业银行\",\"CZCB\":\"浙江稠州商业银行\",\"JXRCU\":\"江西省农村信用\",\"CRCBANK\":\"重庆农村商业银行\",\"SHRCB\":\"上海农村商业银行\",\"ASCB\":\"鞍山银行\",\"BSB\":\"包商银行\",\"XCYH\":\"许昌银行\",\"COMM\":\"交通银行\",\"CSRCB\":\"常熟农村商业银行\",\"NXBANK\":\"宁夏银行\",\"JSB\":\"晋商银行\",\"CMB\":\"招商银行\",\"HURCB\":\"湖北省农村信用社\",\"SPABANK\":\"平安银行\",\"EGBANK\":\"恒丰银行\",\"XXBANK\":\"新乡银行\",\"HBRCU\":\"河北省农村信用社\",\"BOZK\":\"周口银行\",\"CEB\":\"中国光大银行\",\"LSBANK\":\"莱商银行\",\"JHBANK\":\"金华银行\",\"TCCB\":\"天津银行\",\"WHRCB\":\"武汉农村商业银行\",\"NBBANK\":\"宁波银行\",\"LSBC\":\"临商银行\",\"NCB\":\"南昌银行\",\"ZJKCCB\":\"张家口市商业银行\",\"BJRCB\":\"北京农村商业银行\",\"JNBANK\":\"济宁银行\",\"CMBC\":\"中国民生银行\",\"DRCBCL\":\"东莞农村商业银行\",\"BOQH\":\"青海银行\",\"YBCCB\":\"宜宾市商业银行\",\"GDRCC\":\"广东省农村信用社联合社\",\"LZYH\":\"兰州银行\",\"HANABANK\":\"韩亚银行\",\"NJCB\":\"南京银行\",\"YDRCB\":\"尧都农商行\",\"MTBANK\":\"浙江民泰商业银行\",\"JINCHB\":\"晋城银行JCBANK\",\"BOJZ\":\"锦州银行\",\"TZCB\":\"台州银行\",\"LANGFB\":\"廊坊银行\",\"ABC\":\"中国农业银行\",\"CQBANK\":\"重庆银行\",\"SCRCU\":\"四川省农村信用\",\"FDB\":\"富滇银行\",\"XLBANK\":\"中山小榄村镇银行\",\"HSBANK\":\"徽商银行\",\"NXRCU\":\"宁夏黄河农村商业银行\",\"QLBANK\":\"齐鲁银行\",\"WRCB\":\"无锡农村商业银行\",\"BANKWF\":\"潍坊银行\",\"CZBANK\":\"浙商银行\",\"BJBANK\":\"北京银行\",\"HRXJB\":\"华融湘江银行\",\"SRBANK\":\"上饶银行\",\"JSRCU\":\"江苏省农村信用联合社\",\"HKBEA\":\"东亚银行\",\"GZRCU\":\"贵州省农村信用社\",\"HNRCU\":\"河南省农村信用\",\"ZRCBANK\":\"张家港农村商业银行\",\"BOSZ\":\"苏州银行\",\"YXCCB\":\"玉溪市商业银行\",\"BOCD\":\"承德银行\",\"HNRCC\":\"湖南省农村信用社\",\"NHQS\":\"农信银清算中心\",\"XABANK\":\"西安银行\",\"QDCCB\":\"青岛银行\",\"TRCB\":\"天津农商银行\",\"HBHSBANK\":\"湖北银行黄石分行\",\"ARCU\":\"安徽省农村信用社\",\"CZRCB\":\"常州农村信用联社\",\"ZGCCB\":\"自贡市商业银行\",\"URMQCCB\":\"乌鲁木齐市商业银行\",\"HDBANK\":\"邯郸银行\",\"BOHAIB\":\"渤海银行\",\"JRCB\":\"江苏江阴农村商业银行\",\"SDEB\":\"顺德农商银行\",\"HBC\":\"湖北银行\",\"AYCB\":\"安阳银行\",\"SCCB\":\"三门峡银行\",\"LYCB\":\"辽阳市商业银行\",\"FXCB\":\"阜新银行\",\"BODD\":\"丹东银行\",\"XYBANK\":\"信阳银行\",\"WJRCB\":\"吴江农商银行\",\"DYCB\":\"德阳商业银行\",\"BOD\":\"东莞银行\",\"BOC\":\"中国银行\",\"WHCCB\":\"威海市商业银行\",\"CITIC\":\"中信银行\",\"NYNB\":\"广东南粤银行\",\"BGB\":\"广西北部湾银行\",\"BOCY\":\"朝阳银行\",\"CIB\":\"兴业银行\",\"HKB\":\"汉口银行\",\"HBYCBANK\":\"湖北银行宜昌分行\",\"DAQINGB\":\"龙江银行\",\"HXBANK\":\"华夏银行\",\"CDCB\":\"成都银行\",\"PSBC\":\"中国邮政储蓄银行\",\"BOP\":\"平顶山银行\",\"GXRCU\":\"广西省农村信用\",\"SXCB\":\"绍兴银行\",\"SHBANK\":\"上海银行\",\"WZCB\":\"温州银行\",\"GRCB\":\"广州农商银行\",\"H3CB\":\"内蒙古银行\",\"GZB\":\"赣州银行\",\"ZBCB\":\"齐商银行\",\"SZSBK\":\"石嘴山银行\",\"LSCCB\":\"乐山市商业银行\",\"HZCCB\":\"湖州市商业银行\",\"KORLABANK\":\"库尔勒市商业银行\",\"CCQTGB\":\"重庆三峡银行\",\"HSBK\":\"衡水银行\",\"JXBANK\":\"嘉兴银行\",\"KSRB\":\"昆山农村商业银行\",\"DLB\":\"大连银行\",\"SPDB\":\"上海浦东发展银行\",\"FJHXBC\":\"福建海峡银行\",\"BHB\":\"河北银行\",\"ZYCBANK\":\"遵义市商业银行\",\"YQCCB\":\"阳泉银行\",\"SJBANK\":\"盛京银行\",\"XTB\":\"邢台银行\",\"ZJTLCB\":\"浙江泰隆商业银行\",\"NHB\":\"南海农村信用联社\",\"DYCCB\":\"东营市商业银行\",\"FSCB\":\"抚顺银行\",\"DZBANK\":\"德州银行\",\"ZJNX\":\"浙江省农村信用社联合社\",\"CSCB\":\"长沙银行\",\"HZCB\":\"杭州银行\",\"JZBANK\":\"晋中市商业银行\",\"GLBANK\":\"桂林银行\",\"GSRCU\":\"甘肃省农村信用\",\"SRCB\":\"深圳农村商业银行\",\"ZZBANK\":\"郑州银行\",\"TCRCB\":\"江苏太仓农村商业银行\",\"CDRCB\":\"成都农商银行\",\"SDRCU\":\"山东农信\",\"CCB\":\"中国建设银行\",\"CBKF\":\"开封市商业银行\",\"GCB\":\"广州银行\",\"SXRCCU\":\"陕西信合\",\"JLBANK\":\"吉林银行\",\"CBBQS\":\"城市商业银行资金清算中心\",\"TACCB\":\"泰安市商业银行\",\"ORBANK\":\"鄂尔多斯银行\",\"GYCB\":\"贵阳市商业银行\",\"BZMD\":\"驻马店银行\",\"NBYZ\":\"鄞州银行\",\"JSBANK\":\"江苏银行\",\"JLRCU\":\"吉林农信\",\"YNRCC\":\"云南省农村信用社\",\"ICBC\":\"中国工商银行\",\"LYBANK\":\"洛阳银行\"}\n";

    public static String getBank(String cardNumber) {
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + cardNumber + "&cardBinCheck=true";
        OkHttpClient client = new OkHttpClient();
        String getBank = null;
        try {
            getBank = client.newCall(new Request.Builder().url(url).build()).execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("访问支付宝地址失败");
        }
        if (getBank == null || "".equals(getBank)) {
            return "未知";
        }
        String bank = String.valueOf(((JSONObject) JSONObject.parse(getBank)).get("bank"));
        System.out.println("bank>>>>>>" + bank);
        JSONObject string = (JSONObject) JSONObject.parse(BANK_STRING);
        String result = "未知";
        for (String key : string.keySet()) {
            if (key.equals(bank)) {
                System.out.println("key:>>>>>>" + key);
                System.out.println("value:>>>>>>" + string.get(key));
                result = (String) string.get(key);
            }
        }
        return result;
    }



    public static String postSSL(String url, String data, String certPath, String certPass) {
        String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";
        HttpsURLConnection conn = null;
        OutputStream out = null;
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            KeyStore clientStore = KeyStore.getInstance("PKCS12");
            clientStore.load(new FileInputStream(certPath), certPass.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(clientStore, certPass.toCharArray());
            KeyManager[] kms = kmf.getKeyManagers();
            SSLContext sslContext = SSLContext.getInstance("TLSv1");

            sslContext.init(kms, null, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            URL _url = new URL(url);
            conn = (HttpsURLConnection) _url.openConnection();

            conn.setConnectTimeout(25000);
            conn.setReadTimeout(25000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT);
            conn.connect();

            out = conn.getOutputStream();
            out.write(data.getBytes(Charset.forName("UTF-8")));
            out.flush();

            inputStream = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException var3) {
                    var3.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException var3) {
                    var3.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException var3) {
                    var3.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }


    /**
     * httpClient的get请求方式
     * 使用GetMethod来访问一个URL对应的网页实现步骤：
     * 1.生成一个HttpClient对象并设置相应的参数；
     * 2.生成一个GetMethod对象并设置响应的参数；
     * 3.用HttpClient生成的对象来执行GetMethod生成的Get方法；
     * 4.处理响应状态码；
     * 5.若响应正常，处理HTTP响应内容；
     * 6.释放连接。
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset){
        /**
         * 1.生成HttpClient对象并设置参数
         */
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        /**
         * 2.生成GetMethod对象并设置参数
         */
        GetMethod getMethod = new GetMethod(url);
        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理，用的是默认的重试处理：请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        String response = "";

        /**
         * 3.执行HTTP GET 请求
         */
        try {
            int statusCode = httpClient.executeMethod(getMethod);

            /**
             * 4.判断访问的状态码
             */
            if (statusCode != HttpStatus.SC_OK){
                System.err.println("请求出错：" + getMethod.getStatusLine());
            }

            /**
             * 5.处理HTTP响应内容
             */
            //HTTP响应头部信息，这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
//            for (Header h: headers){
//                System.out.println(h.getName() + "---------------" + h.getValue());
//            }
            //读取HTTP响应内容，这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            //读取为InputStream，在网页内容数据量大时候推荐使用
            //InputStream response = getMethod.getResponseBodyAsStream();
        }catch (IOException e){
            //发生网络异常
            System.out.println("发生网络异常!");
        } catch (Exception e) {
            //发生致命的异常，可能是协议不对或者返回的内容有问题
            System.out.println("请求异常!");
            e.printStackTrace();
        } finally {
            /**
             * 6.释放连接
             */
            getMethod.releaseConnection();
        }
        return response;
    }

    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);

        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        //添加请求参数
        postMethod.addParameter("commentId", json.getString("commentId"));

        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

}

